import { http } from '@/utils/request'

// 分类信息
export interface Category {
  id: number
  user_id?: number
  name: string
  icon?: string
  color?: string
  description?: string
  sort: number
  is_system: boolean
  is_active: boolean
  created_at: string
  updated_at: string
  account_count?: number
}

// 创建分类数据
export interface CreateCategoryData {
  name: string
  icon?: string
  color?: string
  description?: string
}

// 更新分类数据
export interface UpdateCategoryData {
  name?: string
  icon?: string
  color?: string
  description?: string
}

// 排序数据
export interface SortCategoryData {
  id: number
  sort: number
}

// 分类统计
export interface CategoryStats {
  id: number
  name: string
  icon?: string
  color?: string
  account_count: number
  is_system: boolean
}

/**
 * 获取分类列表
 */
export const getCategories = () => {
  return http.get<Category[]>('/categories')
}

/**
 * 获取系统分类模板
 */
export const getCategoryTemplates = () => {
  return http.get<Category[]>('/categories/templates')
}

/**
 * 创建分类
 */
export const createCategory = (data: CreateCategoryData) => {
  return http.post<Category>('/categories', data, {
    loading: true,
    loadingText: '创建中...'
  })
}

/**
 * 更新分类
 */
export const updateCategory = (id: number, data: UpdateCategoryData) => {
  return http.put<Category>(`/categories/${id}`, data, {
    loading: true,
    loadingText: '更新中...'
  })
}

/**
 * 删除分类
 */
export const deleteCategory = (id: number) => {
  return http.delete(`/categories/${id}`, {
    loading: true,
    loadingText: '删除中...'
  })
}

/**
 * 分类排序
 */
export const sortCategories = (sorts: SortCategoryData[]) => {
  return http.put('/categories/sort', { sorts }, {
    loading: true,
    loadingText: '保存中...'
  })
}

/**
 * 禁用/启用分类
 */
export const toggleCategoryActive = (id: number) => {
  return http.put<Category>(`/categories/${id}/toggle`, undefined, {
    loading: true
  })
}

/**
 * 复制系统分类
 */
export const copySystemCategories = () => {
  return http.post('/categories/copy-system', undefined, {
    loading: true,
    loadingText: '复制中...'
  })
}

/**
 * 获取分类统计
 */
export const getCategoryStats = () => {
  return http.get<CategoryStats[]>('/categories/stats')
}